<?php

namespace App\Admin\Controllers\Stock;

use App\Models\StockDepot;
use App\Models\StockProduct;
use App\Http\Controllers\Controller;
use App\Models\StockUnit;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;

use function foo\func;

class StockProductController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header(trans('产品管理'))
            ->description(trans('产品'))
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header(trans('admin.detail'))
            ->description(trans('产品'))
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header(trans('admin.edit'))
            ->description(trans('产品'))
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header(trans('admin.create'))
            ->description(trans('产品'))
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new StockProduct);
        $grid->model()->orderByDesc('updated_at');
        $depot_id = Admin::user()->depot_id;
//        $grid->model()->depot()->where('num', '>', 0);
        $unitList = StockUnit::all()->pluck('name', 'id')->toArray();

        if ($depot_id) {
            $stockDepotList = StockDepot::where('id', $depot_id)->get()->pluck('name', 'id')->toArray();
        }else{
            $stockDepotList = StockDepot::all()->pluck('name', 'id')->toArray();
        }

        $grid->id('ID');
        $grid->sn('产品编号');
        $grid->name('产品名称');
        $grid->brand('品牌');
        $grid->price('价格');
        $grid->spec('规格')->style('max-width:300px;word-break:break-all;');;
        $grid->column("depot", "库存")->display(function ($depots){
            $depot_str = "";
            $sum = 0;
            foreach ($depots as $depot){
                $depot_str .= $depot['pivot']['num'] == 0 ?'': $depot['name'].'：'.$depot['pivot']['num'].'<br/>';
                $sum += $depot['pivot']['num'];
            }
            return '总计：'.$sum.'<br/>'.$depot_str;
        });
        $grid->unit('单位')->display(function ($released) use ($unitList) {
            return isset($unitList[$released]) ? $unitList[$released] : "";
        });
        $grid->created_at(trans('admin.created_at'));
        $grid->updated_at(trans('admin.updated_at'));




        $grid->filter(function($filter) use ($stockDepotList){
            $filter->expand();
            $filter->column(1/3, function ($filter) use ($stockDepotList) {
                $filter->where(function ($query) {
                    $query->whereHas('depot', function ($query) {
                        $query->where('depot_id', '=', "{$this->input}")->where('num','>',0);
                    });
                }, '所属仓库')->select($stockDepotList);
            });
            $filter->column(1/3, function ($filter){
                $filter->like('sn', '编号');
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('name', '产品名称');
            });
            $filter->disableIdFilter();// 去掉默认的id过滤器
        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(StockProduct::findOrFail($id));
        $unitList = StockUnit::all()->pluck('name', 'id')->toArray();
        $depotList = StockDepot::all()->pluck('name', 'id')->toArray();
        $show->id('ID');
        $show->sn('产品编号');
        $show->name('产品名称');
        $show->brand('品牌');
//        $show->model('型号');
        $show->spec('规格');
        $show->price('价格');
        $show->unit('单位');
//        $show->supplier('供应商');
        $show->desc('备注')->rules('max:200');
        $show->created_at(trans('admin.created_at'));
        $show->updated_at(trans('admin.updated_at'));



        $show->reports('出入库记录', function (Grid $report) use ($depotList) {
            $report->id('ID');
            $report->sn('出入库编号');
            $report->type('出入库')->using([1=>'入库', 2=>'出库']);
            $report->depot_id('仓库')->using($depotList);
            $report->product_count('数量');
            $report->desc('备注');
//            $report->column('product_count', '总计')->totalRow('合计');
            $report->footer(function ($query) {

                // 查询出已支付状态的订单总金额
                $data = $query->selectRaw('sum(if(type = 1, product_count, 0)) as count1, sum(if(type = 2, product_count, 0)) as count2')->first();
//                var_dump($data);die;
                return "总计（入库：".$data['count1'].'， 出库：'.$data['count2'].'）';
            });
            $report->disableActions();
            $report->disableBatchActions();
            $report->disableFilter();
            $report->disableColumnSelector();
            $report->disableCreateButton();
            $report->disableExport();
            $report->disableTools();
            $report->disablePagination();
        });

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new StockProduct);
        foreach (StockUnit::all() as $item){
            $unitList[$item['id']] = $item['name'];
        };

        $form->text('sn', '产品编号')->default(date("YmdHis").rand(1000, 9999));
        $form->text('name', '产品名称')->rules('max:50');
        $form->text('brand', '品牌')->rules('max:50');
//        $form->text('model', '型号');
        $form->text('spec', '规格')->rules('max:200');
        $form->text('price', '价格');
        $form->select('unit', '单位')->options($unitList);
//        $form->text('supplier', '供应商');
        $form->textarea('desc', '备注')->rules('max:200');
        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();
            $footer->disableReset();
        });
        //保存前回调
//        $form->saving(function (Form $form) {
//            $form->sn = date("YmdHis").rand(1000, 9999);
//        });
        return $form;
    }
}
